import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
import JSONBIG from 'json-bigint'
import {
  Message
} from 'element-ui'
const instance = axios.create({
  baseURL: 'http://api-toutiao-web.itheima.net',
  timeout: 5000,
  // 转换响应数据格式(覆盖默认转换方式) transformResponse执行 ===> 响应拦截器  ===>  then和catch
  transformResponse: [data => {
    // data 其实就是原始的json字符串
    try {
      const jsonObject = JSONBIG.parse(data)
      return jsonObject
    } catch (e) {
      return data
    }
  }]

})
instance.interceptors.request.use(config => {
  // console.log(config);axios实例
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
instance.interceptors.response.use(res => res, err => {
  // console.dir(err.response);
  if (err.response && err.response.status === 401) {
    localStorage.removeItem('token')
    router.push('/login')
  }
  return Promise.reject(err)
  Message({
    message: '失败',
    type: error
  })
})
Vue.prototype.$http = instance
export {
  instance
}
